package com.origin.utils.text

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import androidx.annotation.ColorInt
import com.origin.utils.log.LogUtils

object TextUtils {

    /**
     * @param content 被检索文字
     * @param inputs 热点文字
     * @param foregroundColor 热点文字颜色
     * @param backgroundColor 热点文字背景颜色
     */
    public fun setHotText(
        content: String,
        inputs: List<String>,
        @ColorInt foregroundColor: Int=Color.parseColor("#ff0000"),
        @ColorInt backgroundColor: Int=Color.parseColor("#000000FF"),
    ): SpannableString {
        val spannableString = SpannableString(content)
        inputs.forEach {
            LogUtils.__e("setHotText====> ${it}")
         val points=   findAllHotPoint(content,it)
            points.forEach { point->
                LogUtils.__e("setHotText====> 位置 ${point}")
               val start=  point-(it.length)
                LogUtils.__e("setHotText====> start ${start}")
                if (start>=0){
                    spannableString.setSpan(
                        ForegroundColorSpan(foregroundColor),
                        start,
                        start + it.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    spannableString.setSpan(
                        BackgroundColorSpan(backgroundColor),
                        start,
                        start + it.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
            }

        }
        return spannableString;
    }

    private fun findAllHotPoint( str:String ,key:String):List<Int>{
        var sLin=str
        var frontLength=0;
        val points= mutableListOf<Int>()
        while (sLin.contains(key)){
            val index=sLin.indexOf(key)
            frontLength+=(index+key.length)
            points.add(frontLength)
            sLin=sLin.substring(index+key.length)
        }
        return points;

    }

}